package com.hutao.medical.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.im4java.core.IM4JavaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.hutao.medical.common.config.ConfigProperties;
import com.hutao.medical.common.util.GraphicsMagicUtil;
import com.hutao.medical.common.util.HttpClientUtil;
import com.hutao.medical.common.util.ImageCutUtil;
import com.hutao.medical.common.util.ImageRotateUtil;
import com.hutao.medical.common.util.JsonUtils;
import com.hutao.medical.common.util.Result;
import com.hutao.medical.common.util.TmFileUtil;
import com.hutao.medical.constant.FunctionType;
import com.hutao.medical.mapper.quality.MedicalFunctionMapper;
import com.hutao.medical.mapper.scan.ScanFileMapper;
import com.hutao.medical.mapper.scan.ScanFileRelationMapper;
import com.hutao.medical.mapper.scan.ScanFunctionMapper;
import com.hutao.medical.pojo.quality.MedicalFunction;
import com.hutao.medical.pojo.scan.ScanFile;
import com.hutao.medical.pojo.scan.ScanFileRelation;
import com.hutao.medical.pojo.scan.ScanFunction;
import com.hutao.medical.pojo.vo.OperatorImgVo;
import com.hutao.medical.pojo.vo.QueryScanVo;

@Transactional
@Service
public class ScanService {


	@Autowired
	private MedicalFunctionMapper medicalFunctionMapper;
	
	@Autowired
	private ScanFunctionMapper scanFunctionMapper;

	@Autowired
	private ConfigProperties configProperties;
	
	@Autowired
	private ScanFileMapper scanFileMapper;

	@Autowired
	private ScanFileRelationMapper scanFileRelationMapper;

	
	


	/**
	 * 旋转图片
	 * 
	 * @param imgPath
	 *            图片路径
	 * @param rotate
	 *            旋转角度
	 * @return
	 */
	public String operationImg(String imgPath, Integer rotate, HttpServletRequest request) {
		try {
			// http://localhost:8090/MrDoc/49557184-0/thumbnail_/41/41/1506050664141/1506050691782.png
			// 读取图片文件
			String path = imgPath.substring(configProperties.getServer().getPicHostPath().length());
			String fileUrl = configProperties.getServer().getServerPicFileDir() + path;
			String desFile = fileUrl.substring(0, fileUrl.indexOf(".") + 1) + "jpg";
			BufferedImage src = ImageIO.read(new File(fileUrl));
			BufferedImage des = ImageRotateUtil.Rotate(src, rotate);
			ImageIO.write(des, "jpg", new File(desFile));
			return imgPath.substring(0, imgPath.indexOf(".") + 1) + "jpg";

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 图片裁剪操作
	 * @param operatorImgVo
	 * @throws IOException
	 */
	public void imageCut(OperatorImgVo operatorImgVo) throws IOException {
		String imagePath=configProperties.getServer().getServerPicFileDir()+operatorImgVo.getImgPath();
		//获取原图片高度和宽度
		int sourcePicHeight = GraphicsMagicUtil.getHeight(imagePath);
		int sourcePicWidth = GraphicsMagicUtil.getWidth(imagePath);
		//计算原图片和图片显示框比例
		double heightRate=(double)sourcePicHeight/(double)operatorImgVo.getContainerHeight();
		double widthRate=(double)sourcePicWidth/(double)operatorImgVo.getContainerWidth();
		//根据比例重新计算图片裁剪数据
		double xStart=(double)operatorImgVo.getxStart()*widthRate;
		double yStart=(double)operatorImgVo.getyStart()*heightRate;
		double cutWidth=(double)operatorImgVo.getImgWidth()*widthRate;
		double cutHeight=(double)operatorImgVo.getImgHeight()*heightRate;
		
		GraphicsMagicUtil.cutImage(imagePath, imagePath,  (new Double(xStart)).intValue(), (new Double(yStart)).intValue(), (new Double(cutWidth)).intValue(), (new Double(cutHeight)).intValue());

	}


	/**
	 * 根据firstGuid查询扫描文件路径
	 * @param firstGuid
	 * @return
	 */
	@Transactional(readOnly=true)
	public List<Map<String,Object>> getScanFileListByFirstGuid(String firstGuid){
		return scanFileMapper.getScanFileListByFirstGuid(firstGuid);
	}


	/**
	 * 通过httpclient上传文件
	 * @param folderName
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Result uploadScanFileByHttpClient(QueryScanVo queryScanVo,String operator) {
		Result result = null;
		try {
			MedicalFunction medicalFunction = new MedicalFunction();
			//创建一个扫描记录
			if(medicalFunctionMapper.isExistMedFunctionByFirstGuidAndFunType(queryScanVo.getFirstGuid(), FunctionType.scan)>0){
				medicalFunction =medicalFunctionMapper.getMediFunctionByFirstGuidAndFunType(queryScanVo.getFirstGuid(), FunctionType.scan);
			}else{
				medicalFunction.setCreateTime(new Date());
				medicalFunction.setFirstGuid(queryScanVo.getFirstGuid());
				medicalFunction.setFunctionTypeId(FunctionType.scan);
				medicalFunction.setStatus(1);
				medicalFunctionMapper.insertSelective(medicalFunction);
			}
			ScanFunction  scanFunction = new ScanFunction();
			if(scanFunctionMapper.isExistScanFunctionByMedicalFunctionId(medicalFunction.getId())>0){
				scanFunction=scanFunctionMapper.getScanFunctionByMedicalFunctionId(medicalFunction.getId());
			}else{
				scanFunction.setCreateTime(new Date());
				scanFunction.setMedicalFunctionId(medicalFunction.getId());
				scanFunction.setOperator(operator);
				scanFunctionMapper.insertSelective(scanFunction);
			}
		
			
			HttpClient client = HttpClients.createDefault();// 开启一个客户端 HTTP 请求
			// HTTP POST 请求
			HttpPost post = new HttpPost(configProperties.getMedicalManage().getUploadPicFileByHttpClient());// 创建 HTTP POST 请求
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			//设置请求的编码格式
			ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式
			
			//List<String> scanTempImgList = queryScanVo.getScanImageList();
//			if(CollectionUtils.isEmpty(scanTempImgList)){
//				result=new Result(false,"扫描数据为空!");
//				return result;
//			}
//			int count = 0;
//			for (String scanTempImg : scanTempImgList) {
//				//拼接扫描图片路径
//				
//				String scanTempImgPath = configProperties.getServer().getServerScanImgFileDir()+scanTempImg;		
//				
//				
//				builder.addBinaryBody("file" + count,new File(scanTempImgPath) );
//				count++;
//			}
			
			String scanImage = queryScanVo.getScanImage();
			if(StringUtils.isEmpty(scanImage)){
				result=new Result(false,"扫描数据为空!");
				return result;
			}
			
			String scanTempImgPath = configProperties.getServer().getServerMrDocImgFileDir()+scanImage;		
			builder.addBinaryBody("file",new File(scanTempImgPath) );
			builder.addTextBody("firstGuid",queryScanVo.getFirstGuid() ,contentType);// 设置请求参数
			
			builder.addTextBody("operator",operator ,contentType);
			builder.addTextBody("scanFolderName",scanFunction.getId()+"" ,contentType);
			
			HttpEntity entity = builder.build();// 生成 HTTP POST 实体
			post.setEntity(entity);// 设置请求参数
			HttpResponse response = client.execute(post);// 发起请求 并返回请求的响应
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {

				System.out.println("服务器正常响应.....");

				HttpEntity resEntity = response.getEntity();

				 result = JSONObject.parseObject(EntityUtils.toString(resEntity), Result.class);// httpclient自带的工具类读取返回数据
				
				if(result.isSuccess()){
					List<Map<String,Object>> scanFileList=(List<Map<String, Object>>) result.getData();
					ScanFile scanFile=null;
					for (Map<String, Object> scanFileMap : scanFileList) {
						//{"fileName":"i15r6aki7qhgw4xvuuholxsm690k9ow6zjv8c6wrg1od4aap0wu411v25cro4n7ncb786s2t9p0bpkvciwtgnmxmb0s006x15.jpg","fileHash":"k9kxszm5i15r6aki7qhgw4xvuuholxsm690k9ow6zjv8c6wrg1od4aap0wu411v25cro4n7ncb786s2t9p0bpkvciwtgnmxmb0s006x15","fileUrl":"k9/kx/sz/m5/","fileType":"jpg","createDate":"2018-01-16"}
						scanFile = new ScanFile();
						scanFile.setCreateTime(new Date());
						scanFile.setFileName((String)scanFileMap.get("fileName"));
						scanFile.setFileUrl((String)scanFileMap.get("fileUrl"));
						scanFile.setHash((String)scanFileMap.get("fileHash"));
						scanFileMapper.insertSelective(scanFile);
						
						ScanFileRelation scanFileRelation = new ScanFileRelation();
						scanFileRelation.setCreateTime(new Date());
						scanFileRelation.setScanFileId(scanFile.getId());
						scanFileRelation.setScanFunctionId(scanFunction.getId());
						scanFileRelationMapper.insertSelective(scanFileRelation);
						EntityUtils.consume(resEntity);
					}
					
					
				}else{
					result = new Result(false,"文件上传失败!");
					return result;
				}
			}else{
				result = new Result(false,"文件上传失败!");
				return result;
			}

		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false,"扫描文件异常!");
		}
		return result;

	}
	
	/**
	 * 删除文件扫描信息
	 * @param queryScanVo
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public Result deleteScanFile(QueryScanVo queryScanVo) {
		Result result =null;
		Map<String,String> params = new HashMap<>();
		params.put("firstGuid", queryScanVo.getFirstGuid());
		params.put("fileHash", queryScanVo.getFileHash());
		String responseJson = HttpClientUtil.doPost(configProperties.getMedicalManage().getDeleteScanUploadImg(),params);
		if(StringUtils.isEmpty(responseJson)){
			result = new Result(false,"删除失败,系统无响应!");
			return result;
		}
		result =JsonUtils.jsonToPojo(responseJson, Result.class);
		if(result.isSuccess()){
			
			Map<String,Object> retMap = scanFileMapper.getFileIdByHash(queryScanVo.getFileHash());
			Integer scanFileRelationId =(Integer) retMap.get("scanFileRelationId");
			Integer scanFileId = (Integer) retMap.get("scanFileId");
			scanFileRelationMapper.deleteByPrimaryKey(scanFileRelationId);
			scanFileMapper.deleteByPrimaryKey(scanFileId);
			result = new Result(true,"扫描文件删除成功!");
		}else{
			result = new Result(false,"扫描文件删除失败!");
		}
		
		
		return result;
	}  


	  
    /**
     * 根据图片url下载文件至本地
     * @param urlString
     * @param savePath
     * @param fileName
     * @throws Exception
     */
    public static void download(String urlString,
            String savePath,String fileName) throws Exception {  
        // 构造URL    
        URL url = new URL(urlString);  
        // 打开连接    
        URLConnection con = url.openConnection();  
        //设置请求超时为5s    
        con.setConnectTimeout(5 * 1000);  
        // 输入流    
        InputStream is = con.getInputStream();  
  
        // 1K的数据缓冲    
        byte[] bs = new byte[1024];  
        // 读取到的数据长度    
        int len;  
        // 输出的文件流    
        File sf = new File(savePath);  
        if (!sf.exists()) {  
            sf.mkdirs();  
        }  
        OutputStream os = new FileOutputStream(savePath+"\\"+fileName);  
        // 开始读取    
        while ((len = is.read(bs)) != -1) {  
            os.write(bs, 0, len);  
        }  
        // 完毕，关闭所有链接    
        os.close();  
        is.close();  
    }

    /**
     * 旋转图片
     * @param queryScanVo
     * @throws IM4JavaException 
     * @throws InterruptedException 
     * @throws IOException 
     */
	public void rotateImg(QueryScanVo queryScanVo) throws IOException, InterruptedException, IM4JavaException {
		String imgPath=configProperties.getServer().getServerPicFileDir()+queryScanVo.getImgPath();
		GraphicsMagicUtil.rotate(imgPath, imgPath, queryScanVo.getAngle());
	}


  

	
    
    
 
	
	
	
	

}
